package com.threadlocal;

import java.util.Date;
import java.util.Random;

/**
 * @PackageName:com.threadlocal
 * @ClassName:Test03
 * @Description: ThreadLocal初始值
 * @Author: zhangxiaoyu
 * @date 2021/1/18 16:58
 */
public class Test03 {

    //01.定义一个ThreadLocal的子类
    static  class SubThreadLocal extends ThreadLocal<Date>{

        //02.重写initialValue方法，设置初始值
        @Override
        protected Date initialValue() {
            return new Date(); //把当前日期设置为初始值
        }
    }

    //定义对象
    //static ThreadLocal threadLocal = new ThreadLocal();

    static SubThreadLocal threadLocal = new SubThreadLocal();

    //定义线程
    static class SubThread extends Thread{
        @Override
        public void run() {
            for (int i =0;i<10;i++){
                //第一次调用threaLocal的get()方法会返回null
                System.out.println("-----"+Thread.currentThread().getName()+"value="+threadLocal.get());
                //如果没有初始值就设置当前日期
                if(threadLocal.get()==null){
                    System.out.println("========================================");
                    threadLocal.set(new Date());
                }
                try {
                    Thread.sleep(new Random().nextInt(500));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static void main(String[] args){
        SubThread t1 = new SubThread();
        t1.start();
        SubThread t2 = new SubThread();
        t2.start();
    }
}
